package com.jsh.ex.handler;

import com.jsh.ex.common.ErrorInfo;
import com.jsh.ex.exception.MyException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常处理
 * Created by wukai on 2017/4/22.
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req,Exception e) throws Exception{
        ModelAndView mav = new ModelAndView();
        logger.info("url:"+req.getRequestURL()+",ex:"+e.getMessage());
        mav.addObject("exception",e.getMessage());
        mav.addObject("url",req.getRequestURL());
        mav.setViewName("myError");
        return mav;
    }

    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ErrorInfo<String> jsonErrorHandler(HttpServletRequest req, MyException e) throws  Exception{
        ErrorInfo<String> r = new ErrorInfo<String>();
        r.setMessage(e.getMessage());
        r.setCode(ErrorInfo.ERROR);
        r.setData("sssss");
        r.setUrl(req.getRequestURL().toString());
        return r;
    }
}
